package edu.study.ops.controller;

import edu.study.api.common.dto.RespDto;
import edu.study.api.common.enums.BaseResultCodeEnum;
import edu.study.common.exception.BizException;
import edu.study.common.exception.ExceptionHandler;
import edu.study.common.util.log.Loggers;
import edu.study.common.validation.RequestValidator;
import edu.study.ops.config.OpsConstant;
import edu.study.ops.dto.UploadSplitFileBeforeDto;
import edu.study.ops.req.UploadSplitFileBeforeReq;
import edu.study.ops.req.UploadSplitFileReq;
import edu.study.ops.service.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;

@RestController
@RequestMapping("/api/ops/oss")
@Api(value = "/api/ops/oss", produces = "oss上传文件")
public class UploadApiImpl {
	
	@Autowired
	private OpsConstant opsConstant;

    @Autowired
    private OssService ossService;

	@ApiOperation("上传")
    @RequestMapping(path = "upload", method = RequestMethod.POST)
    public RespDto<String> upload(@RequestParam("file") MultipartFile file) {
		RespDto<String> resp = new RespDto<String>();
        try {
        	String fileName = file.getOriginalFilename();
        	int pos = fileName.lastIndexOf('.');
        	if (pos == -1) {
        		throw new BizException(BaseResultCodeEnum.FILE_NOT_ALLOWED);
        	}
    		String str = fileName.substring(pos, fileName.length());//.文件后缀名
    		if (".xls".equalsIgnoreCase(str) || ".xlsx".equalsIgnoreCase(str) || ".doc".equalsIgnoreCase(str) || ".docx".equalsIgnoreCase(str) || ".pdf".equalsIgnoreCase(str) || ".bmp".equalsIgnoreCase(str) || ".jpg".equalsIgnoreCase(str) || ".png".equalsIgnoreCase(str) || ".gif".equalsIgnoreCase(str) || ".jpeg".equalsIgnoreCase(str) || ".zip".equalsIgnoreCase(str) || ".rar".equalsIgnoreCase(str)) {
    			String ossName;
    			if (file.getSize() < opsConstant.getUploadFileSize() * 1024 * 1024L) {
    				ossName = ossService.uploadFileWithTimeStamp(new ByteArrayInputStream(file.getBytes()), file.getOriginalFilename());
    			} else {
    				ossName = ossService.uploadFileWithSplit(file);
    			}
    			resp.setData(ossName);
    			Loggers.api.info("UploadApiImpl.upload() uploadFile={}, ossName={}", file.getOriginalFilename(), ossName);
    		} else {
    			throw new BizException(BaseResultCodeEnum.FILE_NOT_ALLOWED);
    		}
			return resp;
        } catch (Throwable t) {
        	resp = ExceptionHandler.handleFailFast(resp, t);
        	Loggers.api.info("<==UploadApiImpl.upload() end, resp={}", resp);
            return resp;
        }
    }
	
	@ApiOperation("分片上传文件前")
    @RequestMapping(path = "uploadSplitFileBefore", method = RequestMethod.POST)
    public RespDto<UploadSplitFileBeforeDto> uploadSplitFileBefore(@RequestBody UploadSplitFileBeforeReq req) {
		RespDto<UploadSplitFileBeforeDto> resp = new RespDto<UploadSplitFileBeforeDto>();
        try {
        	String fileName = req.getFileName();
        	if (StringUtils.isEmpty(fileName)) {
        		throw new BizException(BaseResultCodeEnum.INVALID_REQUEST_PARAM);
        	}
        	int pos = fileName.lastIndexOf('.');
        	if (pos == -1) {
        		throw new BizException(BaseResultCodeEnum.FILE_NOT_ALLOWED);
        	}
    		String str = fileName.substring(pos, fileName.length());//.文件后缀名
    		if (".xls".equalsIgnoreCase(str) || ".xlsx".equalsIgnoreCase(str) || ".doc".equalsIgnoreCase(str) || ".docx".equalsIgnoreCase(str) || ".pdf".equalsIgnoreCase(str) || ".bmp".equalsIgnoreCase(str) || ".jpg".equalsIgnoreCase(str) || ".png".equalsIgnoreCase(str) || ".gif".equalsIgnoreCase(str) || ".jpeg".equalsIgnoreCase(str) || ".zip".equalsIgnoreCase(str) || ".rar".equalsIgnoreCase(str)) {
    			resp = ossService.uploadSplitFileBefore(req.getFileName());
    		} else {
    			throw new BizException(BaseResultCodeEnum.FILE_NOT_ALLOWED);
    		}
			Loggers.api.info("UploadApiImpl.uploadSplitFileBefore(), ossName={}", resp);
			return resp;
        } catch (Throwable t) {
        	resp = ExceptionHandler.handleFailFast(resp, t);
        	Loggers.api.info("<==UploadApiImpl.uploadSplitFileBefore() end, resp={}", resp);
            return resp;
        }
    }
	
	@ApiOperation("分片上传文件")
    @RequestMapping(path = "uploadSplitFile", method = RequestMethod.POST)
    public RespDto<String> uploadSplitFile(@RequestBody UploadSplitFileReq req) {
		RespDto<String> resp = new RespDto<String>();
        try {
        	RequestValidator.validate(req);
        	String ossName = ossService.uploadSplitFile(req.getInstream(), req.getPartSize(), req.getPartNo(), req.getPartCount(), req.getFileName(), req.getUploadId());
			resp.setData(ossName);
			Loggers.api.info("UploadApiImpl.uploadSplitFile(), ossName={}", ossName);
			return resp;
        } catch (Throwable t) {
        	resp = ExceptionHandler.handleFailFast(resp, t);
        	Loggers.api.info("<==UploadApiImpl.uploadSplitFile() end, resp={}", resp);
            return resp;
        }
    }
}
